package service

import (
	"context"
	"strconv"

	"github.com/go-kratos/kratos/v2/log"

	pb "poetize/api/sys_config/v1"
	"poetize/app/service/sys_config/internal/biz"
)

type ConfigMessageService struct {
	pb.UnimplementedConfigMessageServer
	cc  *biz.ConfigUseCase
	log *log.Helper
}

func NewConfigMessageService(cc *biz.ConfigUseCase, logger log.Logger) *ConfigMessageService {
	return &ConfigMessageService{
		cc:  cc,
		log: log.NewHelper(logger),
	}
}

func (s *ConfigMessageService) SaveConfig(ctx context.Context, req *pb.SaveConfigRequest) (*pb.SaveConfigReply, error) {
	ids := req.GetId()
	id, _ := strconv.Atoi(ids)

	res, err := s.cc.CreateConfig(ctx, id, req.GetConfigName(), req.GetConfigKey(), req.GetConfigValue(), req.GetConfigType())
	if res == 0 {
		return &pb.SaveConfigReply{}, err
	}
	return &pb.SaveConfigReply{
		Id: uint64(res),
	}, nil
}

func (s *ConfigMessageService) DeleteConfig(ctx context.Context, req *pb.SaveConfigRequest) (*pb.DelConfigReply, error) {
	id, _ := strconv.Atoi(req.GetId())
	res, err := s.cc.DeleteConfig(ctx, id)
	if res == 0 {
		return &pb.DelConfigReply{}, err
	}
	return &pb.DelConfigReply{
		Id: uint64(id),
	}, nil
}

func (s *ConfigMessageService) ListConfig(ctx context.Context, req *pb.ListConfigRequest) (*pb.ListConfigReply, error) {
	page := req.GetPage()
	size := req.GetSize()
	name := req.GetConfigName()
	key := req.GetConfigKey()
	value := req.GetConfigValue()
	types := req.GetConfigType()
	res, err := s.cc.ListConfig(ctx, name, key, value, types, int(size), int(page))
	if err != nil {
		return &pb.ListConfigReply{
			Code:              400,
			Message:           err.Error(),
			Data:              nil,
			CurrentTimeMillis: "",
		}, err
	}
	list := make([]*pb.Configs, 0)
	for _, re := range res {
		list = append(list, &pb.Configs{
			Id:          int32(re.Id),
			ConfigName:  re.ConfigName,
			ConfigKey:   re.ConfigKey,
			ConfigValue: re.ConfigValue,
			ConfigType:  re.ConfigType,
		})
	}
	return &pb.ListConfigReply{
		Code:              200,
		Message:           "获取成功",
		Data:              list,
		CurrentTimeMillis: "",
	}, nil
}

func (s *ConfigMessageService) ListsConfig(ctx context.Context, req *pb.ListConfigRequest) (*pb.ListConfigReply, error) {
	return &pb.ListConfigReply{
		Code:              200,
		Message:           "",
		Data:              nil,
		CurrentTimeMillis: "",
	}, nil
}
